package com.bandit.registry.zk;

import com.bandit.emums.RpcExceptionMessageEnum;
import com.bandit.exception.RpcException;
import com.bandit.registry.ServiceDiscovery;
import com.bandit.registry.zk.utils.CuratorUtils;
import com.bandit.remoting.dto.RpcRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @author Bandit
 * @create 2022/2/24 10:51
 */
@Slf4j
public class ZkServiceDiscoveryImpl implements ServiceDiscovery {
    @Override
    public InetSocketAddress lookupService(RpcRequest rpcRequest) {
        String rpcServiceName = rpcRequest.getRpcServiceName();
        log.info("LookingUp Service Named:[{}] ...",rpcServiceName);
        CuratorFramework zkClient = CuratorUtils.getZkClient();
        //  /my-rpc/com.bandit.HelloService/127.0.0.1:9999
        List<String> childrenNodes = CuratorUtils.getChildrenNodes(zkClient, rpcServiceName);
        if(childrenNodes==null||childrenNodes.size()==0){
            throw new RpcException(RpcExceptionMessageEnum.SERVICE_CAN_NOT_BE_FOUND,rpcServiceName);
        }
        //targetServiceUrl : eg: 127.0.0.1:9998
        String targetServiceUrl = childrenNodes.get(0);
        String[] split = targetServiceUrl.split(":");
        String host = split[0];
        int port = Integer.parseInt(split[1]);
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        log.info("Lookup Service Info:{ host:[{}] port:[{}] InetSocketAddress:[{}]}",host,port,inetSocketAddress);
        return inetSocketAddress;
    }
}
